#!/usr/bin/ruby
#
# Twitachu - Lightweight twitter reader that displays tweets through libnotify
# (C) 2011 Artur Sowiński <artur.sowinski@gmail.com>
# http://PleasantHacking.com
# Released under MIT license:
#

# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the “Software”), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

require "rubygems"
require "twitter"
require "oauth"


# delay in seconds between each request against twitter api 
# keep in mind access is rate limited to about 300 requests/hour
delay = 25

# print out extra messy debug info
debug = false

# setup ico cache dir
ico_dir = ENV['HOME']+ "/.twitachu"
conf_file = ico_dir + "/config"
Dir.mkdir(ico_dir) unless File.directory?(ico_dir)
Dir.chdir(ico_dir)


# get oauth bruhaha out of the way
twitachu_consumer_key = "aE8FaEcm96veFQck4GRLhWxmZDTQc9R5vStkq0U14Lyn2XCiJNjOurFHehbAKGPl6BoI8Wfd7YgMVzspaw3E"
twitachu_consumer_secret = "7D53S1Epj3OFwOvIapd9FmfG3ewQZLCASmGKCEvBC8xmZDTQc9R5vStkq0U14Lyn2XCiJNjOurFHehbAKGPl6BoI8Wfd7YgMVzspaw3EQFsjHWxS2tZGIgdmp0PLEChJ1roM6nNfO3URqA8aK49BzDkliwYXuv5bVcyTe7"

if File.exist?(conf_file)
    load conf_file
    user_token = $cf_user_token
    user_secret = $cf_user_secret

else
    consumer = OAuth::Consumer.new twitachu_consumer_key.tr(twitachu_consumer_secret[104..1000],
        twitachu_consumer_key[22..1000])[0..21], twitachu_consumer_secret.tr(twitachu_consumer_key[22..1000],
        twitachu_consumer_secret[104..1000])[0..41], 
          { :site => 'http://twitter.com/',
            :request_token_path => '/oauth/request_token',
            :access_token_path => '/oauth/access_token',
            :authorize_path => '/oauth/authorize'}
     
    # get token from twitter by the url -> pin auth path
    request_token = consumer.get_request_token
    puts "Place \"#{request_token.authorize_url}\" in your browser"
    print "Enter the number they give you: "
    pin = STDIN.readline.chomp
    access_token = request_token.get_access_token(:oauth_verifier => pin)

    user_token = access_token.token
    user_secret = access_token.secret

    # save tokens for later
    cf = File.new(conf_file, "w+")
    cf.puts '$cf_user_token="'+user_token+'"'
    cf.puts '$cf_user_secret="'+user_secret+'"'
    cf.close
end

# setup oauth for Twitter
Twitter.configure do |config|
  config.consumer_key = twitachu_consumer_key.tr(twitachu_consumer_secret[104..1000], 
twitachu_consumer_key[22..1000])[0..21]
  config.consumer_secret = twitachu_consumer_secret.tr(twitachu_consumer_key[22..1000], 
twitachu_consumer_secret[104..1000])[0..41]
  config.oauth_token = user_token
  config.oauth_token_secret = user_secret
end

# setup twitter client
client = Twitter::Client.new

# put up a nice message and lets go
puts "Twitachu - lets go tweetin"


last_id = 1

# master loop
while true
    begin
	    timeline = client.home_timeline( :count => 20 , :since_id => last_id )

	    last_id = timeline[0].id unless timeline.empty?

	    timeline.reverse.each do|st|
		    # simple and crude follow-spam detection, insensitive to the utf8 poo that might occur
		    break if st.text.gsub(/[^a-z0-9@\.]+/i, ' ') =~ /follow(ing)* @([a-z0-9]+)/i
	    
		    # setup ico file
		    ico_url = st.user.profile_image_url
		    ico_file = ico_dir + "/" + ico_url.gsub(/[^a-z0-9\.]+/i, '-')
		    system("wget", "-c", ico_url, "-O", ico_file, "--quiet") unless File.exists?(ico_file)

		    # the notify-send itself
		    system("notify-send", "-i", ico_file, st.user.name, st.text)
	
		    # display whats going on in commandline
		    puts "::: #{st.user.name} (@#{st.user.screen_name})"
		    puts Time.now
		    puts st.text
		    puts st if debug
		    puts
	    end

	    # some debug info
	    puts client.rate_limit_status.remaining_hits.to_s + " Twitter API request(s) remaining this hour" if debug
    rescue Exception => e
    	puts "!!! Some twitter error happened..."
    	puts e.message
    	puts
    end

    # wait for screensaver if its active
    sleep 1 while `gnome-screensaver-command -q`["is active"]

    # wait for next tweets
    sleep delay
end


